class SubmitController < ApplicationController
  
  before_filter :submitted, :only => [:attach_files, :edit, :check, :final_submit]
  before_filter :before
  
  def start
    
  end
  
  def form
    @proposal = Proposal.new
    
  end
  
  def create
    @proposal = Proposal.new(params[:proposal])

      if @proposal.save
        flash[:notice] = "Antrag wurde erfolgreich erstellt."
        redirect_to "/submit/attach_files/#{@proposal.id.to_s}"
      else        
        render :action => "form"
      end
  end
  
  def attach_files
   @proposal = Proposal.find(params[:id])
   @documents = @proposal.documents.find(:all)
   @document = @proposal.documents.build
  end
 
  def edit
   @proposal = Proposal.find(params[:id])
  end
 
  def check
   @proposal = Proposal.find(params[:id])
   @documents = @proposal.documents.find(:all)
   
  end
 
  def thanks
    @proposal = Proposal.find(params[:id])
    @documents = @proposal.documents.find(:all)

  end

  def view
    @proposal = Proposal.find(params[:id])
    @documents = @proposal.documents.find(:all)
    @review = Review.new
  end
  
  def index
    @query = params[:email]
    @proposals = Proposal.find( :all, :conditions =>{ :email => @query})
  end
  
  def final_submit
   @proposal = Proposal.find(params[:id])
   @documents = @proposal.documents.find(:all)
      
   if @proposal.update_attributes(params[:proposal])
        flash[:notice] = 'Proposal was successfully updated. test'
        if @proposal.status != 'new'
          Emailer.deliver_new_submission(ADMIN_EMAIL, @proposal)
          Emailer.deliver_new_submission(@proposal[:email], @proposal)
          redirect_to "/submit/thanks/#{@proposal.id.to_s}"
        else
          flash[:error] = 'Bitte Checkbox anklicken, um zu bestätigen, dass der Antrag komplett ist.'    
          redirect_to "/submit/check/#{@proposal.id.to_s}"
        end
   else
           render :action => "edit"
   end     
  end
 
 
  private

  def before
    unless session[:user_id].nil?
      @user = User.find(session[:user_id])
    end
  end
  
  def submitted
     
    @proposal = Proposal.find(params[:id])
    unless (@proposal.status == "new")
     flash[:error] = 'Der Antrag ist definitiv eingereicht und kann nicht mehr abgeändert werden.'    
     render :action => "thanks"
     return false
     exit
    end
  end


end
